package bot

import (
	"bufio"
	"io"
	"math/rand"
	"net/http"
	"os"
	"time"

	logger "github.com/sirupsen/logrus"
)

type ProgramHandler struct {
	currentProgramNumber int
}

func NewProgramHandler() *ProgramHandler {
	return &ProgramHandler{currentProgramNumber: 0}
}

func (program *ProgramHandler) Sleep() int {
	logger.Info("=== sleep started ")
	r := rand.Intn(3) + 2
	time.Sleep(time.Duration(r) * time.Second)
	logger.Info("=== sleep started ")
	return r
}

func (program *ProgramHandler) GetCurrentRunProgram(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		logger.Info("Numver ", program.currentProgramNumber)
		inputFile := "webserver/assets/bot/program/program_getCurrentProgram_empty.json"
		if program.currentProgramNumber%2 == 0 {
			logger.Info(" 进来了")
			inputFile = "webserver/assets/bot/program/program_getCurrentProgram.json"
		} else {
			logger.Info(" 没进来了")
		}

		inputReader, error := os.Open(inputFile)
		if error != nil {
			logger.Error(error)
		} else {
			inputReader := bufio.NewReader(inputReader)
			w.Header().Set("Content-Type", "application/json")
			r.ParseForm()
			io.Copy(w, inputReader)
		}
	}
	program.currentProgramNumber++
}

func (program *ProgramHandler) GetProgramList(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		inputFile := "webserver/assets/bot/program/program_getProgramList.json"

		inputReader, error := os.Open(inputFile)
		if error != nil {
			logger.Error(error)
		} else {
			inputReader := bufio.NewReader(inputReader)
			w.Header().Set("Content-Type", "application/json")
			r.ParseForm()
			io.Copy(w, inputReader)
		}
	}
}
